import { Connection as JsforceConnection } from 'jsforce';
import { Record } from './models';
import { SoqlBuilder } from './queryBuilder';

export interface SalesforceAPI {
  create(type: string, records: Array<Record>): Promise<RecordResult | RecordResult[]>;
  query<T>(query: SoqlBuilder): Promise<Record<T>[]>;
}

export type RecordResult = SuccessResult | ErrorResult;

export const getApi = (connection: JsforceConnection): SalesforceAPI =>
  new SalesforceAPIOfJsForceConnection(connection);

interface ErrorResult {
  errors: string[];
  success: false;
}

interface SuccessResult {
  id: string;
  success: true;
}

class SalesforceAPIOfJsForceConnection implements SalesforceAPI {
  constructor(private readonly connection: JsforceConnection) {}

  public create(type: string, records: any[]): Promise<RecordResult | RecordResult[]> {
    return this.connection.create(type, records);
  }

  public async query<T>(query: SoqlBuilder): Promise<Record<T>[]> {
    const queryResult = await this.connection.query<Record<T>>(query.toSoql());
    return queryResult.records;
  }
}
